import { h, fragment } from '@knno/dom/jsx';
import { renderToString } from '@knno/dom';
import { Chapter } from '../cmd/openBook';
import style from './style.css';

export async function generateHTML(chapters: Chapter[], firstChapterText: string) {
	// const text = (await gunzipPromise(chapters[0].gzip_content)).toString('utf-8');
	return renderToString(() => {
		return (
			<html lang="zh-CN">
				<head>
					<meta charset="utf-8" />
					<meta name="viewport" content="width=device-width, initial-scale=1.0" />
					<style>{style}</style>
					<script>{`
						window.addEventListener('message', event => {
							const div = document.getElementById('chapterContent');
							div.textContent = event.data;
							const box = document.getElementById('contentBox');
							box.scrollTop = 0;
						});
						const chapters = ${JSON.stringify(chapters)};
						let current = 0;
						const vscode = acquireVsCodeApi();
						function openChapter(id) {
							current = id;
							[...document.querySelectorAll('div.navBar>span')].forEach((span) => span.textContent = chapters[id].chapter);
							vscode.postMessage({
								command: 'openChapter',
								id: chapters[id].id,
							});
						}
						function openNext() {
							if (current < chapters.length - 1) {
								openChapter(current + 1);
							}
						}
						function openPrevious() {
							if (current > 0) {
								openChapter(current - 1);
							}
						}
				`}</script>
				</head>
				<body>
					<div style={{ display: 'flex', flex: 1, height: 0, flexDirection: 'row' }}>
						<div
							id="contentBox"
							style={{
								flex: 1,
								overflowY: 'auto',
								whiteSpace: 'pre-line',
								fontFamily: '楷体',
								fontSize: '15pt',
								lineHeight: '125%',
								padding: '2em',
								color: '#aaa',
							}}>
							<div class="navBar">
								<button onclick="openPrevious()">上一章</button>
								<span>{chapters[0].chapter}</span>
								<button onclick="openNext()">下一章</button>
							</div>
							<div id="chapterContent">{firstChapterText}</div>
							<div class="navBarBottom">
								<button onclick="openPrevious()">上一章</button>
								&nbsp;&nbsp;
								<button onclick="openNext()">下一章</button>
							</div>
						</div>
						<div style={{ width: '300px', overflow: 'auto' }}>
							{...chapters.map((chapter, idx) => (
								<div class="index-row" onclick={`openChapter(${idx})`}>
									{chapter.chapter}
								</div>
							))}
						</div>
					</div>
				</body>
			</html>
		);
	});
}
